/*
 * @Date         : 2022-06-08 22:26:22
 * @LastEditors  : zu1662
 * @LastEditTime : 2024-05-24 15:00:06
 * @Description  : alioss service
 *
 * Copyright © 2022 by zu1662, All Rights Reserved.
 */
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { OssClient } from './oss.client';
import { OssInfo } from './oss.interface';
import { AliyunOssClient } from './ossClients/oss.aliyun';
import { TencentOssClient } from './ossClients/oss.tencent';
import { ConfigService } from '@nestjs/config';
import { DebuggerService } from 'src/debugger/service/debugger.service';

@Injectable()
export class OssService {
  ossClient: OssClient;
  private readonly ossInfo: OssInfo;

  constructor(
    private readonly debuggerService: DebuggerService,
    private readonly configService: ConfigService
  ) {
    const ossType = this.configService.get<string>('oss.type');
    const ossAccessId = this.configService.get<string>('oss.accessId');
    const ossAccessSecret = this.configService.get<string>('oss.accessSecret');
    const ossBucket = this.configService.get<string>('oss.bucket');
    const ossRegion = this.configService.get<string>('oss.region');
    this.ossInfo = {
      ossType,
      ossAccessId,
      ossAccessSecret,
      ossBucket,
      ossRegion,
    };
  }

  async initClient() {
    if (!Object.keys(this.ossInfo).length)
      throw new HttpException('OSS 配置不完善，无法进行操作', HttpStatus.BAD_REQUEST);

    if (this.ossClient) return;
    const ossType = this.ossInfo.ossType.toLocaleLowerCase();
    if (ossType === 'aliyun') {
      this.ossClient = new AliyunOssClient(this.ossInfo);
    } else if (ossType == 'tencent') {
      this.ossClient = new TencentOssClient(this.ossInfo);
    }
  }

  // 上传文件
  async putItemInBucket(
    filename: string,
    content: string | Uint8Array | Buffer | ReadableStream | Blob,
    options?: any
  ): Promise<string> {
    await this.initClient();
    return await this.ossClient.putFile(filename, content, options);
  }

  // 删除文件
  async deleteItemInBucket(filename: string): Promise<boolean> {
    await this.initClient();
    return await await this.ossClient.deleteFile(filename);
  }

  // 删除多个文件
  async deleteItemsInBucket(filenames: string[]): Promise<boolean> {
    await this.initClient();
    return await await this.ossClient.deleteFiles(filenames);
  }
}
